<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Events\RepayMentEvent;
use App\Models\RepayRecord;
use App\Models\RepayRecordMoney;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class RepayJobQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    protected $id;

    /**
     * RepayJobQueue constructor.
     * @param $id
     */
    public function __construct($recordId)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_MONEY);
        $this->id = $recordId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        //资方 && 资方 => 月保费 => 公共
        DB::beginTransaction();
        try {
            //获取还款记录
            $recordInfo = RepayRecord::with(['money','month','common'])->where('id',$this->id)->first();
            if(!$recordInfo){
                Log::debug('还款:请求资方接口:没有数据' . $this->id);
                return;
            }

            //todo 判断是否是农信的
            $is_channel = RepaySummary::getLoanChannel($recordInfo->summary_id);
            if(false == $is_channel){
                Log::debug('还款:请求资方接口:是农信的' . $this->id);
                DB::commit();
                return;
            }


            //判断当前在队列中的是否是要处理的状态,1 and 3
            if($recordInfo->money->status == RepayRecordMoney::STATUS_TWO || $recordInfo->money->status == RepayRecordMoney::STATUS_FOUR){
                Log::debug('还款:请求资方接口:在队列中不是要处理的状态' . $this->id);
                return;
            }

            //判断上期是否还款成功
            $is_success = RepayRecord::isLastPeriodSuccess($recordInfo);
            if(!$is_success){
                RepayRecordMoney::where('id',$recordInfo->money->id)->update(['status' => RepayRecordMoney::STATUS_THREE,'failure' => '请还上期还款']);
                RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_THREE,'failure_status' => RepayRecord::FAILURE_STATUS_THREE,'failure_message' => '请还上期还款']);
                UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);
                Log::debug('repay_last_period_success', ['message' => json_encode($recordInfo,JSON_UNESCAPED_UNICODE)]);
                DB::commit();
                return;
            }
            //获取还款计划表,查看是否更新为成功,代码待优化
            $flag = $this->getRepayPlanStatus($recordInfo);
            if($flag){
                //更新催收方数据
                event(new RepayMentEvent($recordInfo->summary_id));
                RepayMonthJobQueue::dispatch($recordInfo->id);
                DB::commit();
                return;
            }
            $tradeNo = RepaySummary::createTradeNo($recordInfo->uid,'money');
            $res = RepaySummary::setMoney($recordInfo,$tradeNo);
            if(!$res){
                DB::commit();
                return;
            }
            //改变状态为轮询
            UserGlobal::where('uid',$recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_ING]);
            RepayRecord::where('id',$recordInfo->id)->update(['status' => RepayRecord::STATUS_TWO]);
            RepayRecordMoney::where('id',$recordInfo->money->id)->update(['status'=>RepayRecordMoney::STATUS_TWO,'trade_no' => $tradeNo]);
            RepaySummary::checkApiNumber($recordInfo->summary_id,$recordInfo->uid,RepaySummary::MONEY_API,2);
            DB::commit();
        } catch (\Exception $e) {
            \Log::debug('还款:调用资方接口队列失败' . $e->getFile() . '的' . $e->getLine() . '行中' . $e->getMessage() . '导致此次队列执行失败' . PHP_EOL);
            DB::rollBack();
        }

    }

    protected function getRepayPlanStatus(RepayRecord $recordInfo){
        if($recordInfo->period == 0){
            return false;
        }
        $summaryInfo = RepaySummary::select(['loan_id','loan_channel','data_type','loan_request_id'])->where('id',$recordInfo->summary_id)->first();
        return $this->getMoneyPlan($summaryInfo->loan_id,$recordInfo->money);

    }

    /**
     * Description:获取计划表
     * Author:lijiafei
     * @param $loan_id
     * @param $period
     * @param RepayRecordMoney $model
     * @return bool
     */
    protected function getMoneyPlan($loan_id,RepayRecordMoney $model)
    {
        $data = RepaySummary::mapMoneyDataFromThirdApi($loan_id,$model->period);
        if(!$data){
            return false;
        }
        //判断是否支付成功
        $status = isset($data['status']) ? $data['status'] : '';
        if(empty($status)){
            return false;
        }
        $is_success = RepayRecordMoney::getMoneyPlanStatus($status);
        if($is_success){
            //把当前改为成功
            \DB::beginTransaction();
            RepayRecordMoney::setMoneySuccessStatus($model,$data);
            \DB::commit();
            return true;
        }else{
            DB::rollBack();
            return false;
        }

    }
}
